package com.hxh.spring.cloud.emoticon.produce.controller;

import com.hxh.spring.cloud.emoticon.produce.config.ThreadPoolConfig;
import com.hxh.spring.cloud.emoticon.produce.entity.Emoticon;
import com.hxh.spring.cloud.emoticon.produce.service.impl.EmoticonServiceImpl;
import com.hxh.spring.cloud.emoticon.produce.thread.*;
import com.hxh.spring.cloud.emoticon.produce.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author huangxunhui
 * Date: Created in 2019-05-08 21:43
 * Utils: Intellij Idea
 * Description:
 */
@Slf4j
@RestController
public class EmoticonController {

    @Autowired
    private EmoticonServiceImpl emoticonService;

    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    private volatile ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();

    @Autowired
    private RedisUtil<String> redisUtil;

    @Autowired
    private RedisUtil<Emoticon> emoticonRedisUtil;

    @PostConstruct
    public void init() {
        queue.offer("2017-09-09 09:10:00");
    }

    @GetMapping("/setUrl")
    public String setUrl(){
        for (int i = 1; i <= 4317; i++) {
            redisUtil.setHash("reqUrl" , i+"" ,"https://fabiaoqing.com/biaoqing/lists/page/"+i);
        }
        return "Suc";
    }

    @GetMapping("/setDoutula")
    public String setDoutula(){
        for (int i = 1; i <= 2437; i++) {
            redisUtil.setHash("doutula" , i+"" ,"https://www.doutula.com/photo/list/?page="+i);
        }
        return "Suc";
    }

    @GetMapping("/produce")
    public String produce() {

        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = threadPoolConfig.getThreadPool();

        List<String> reqUrls = redisUtil.getHashAllValue("doutula");

        for (String reqUrl : reqUrls) {
            threadPoolExecutor.execute(() -> new EmoticonThread(reqUrl , "img-responsive lazy image_dta", emoticonService ,redisUtil).run());
        }

        return "全部线程执行完毕";
    }

    @GetMapping("/produceByJson")
    public String produceByJson(){
        new ProduceThread(redisUtil,queue).run();
        return "SUC";
    }

    @GetMapping("/downloadUrl")
    public String downloadUrl(){
        // 生成文件
        String fileName = "/Users/code/Desktop/url.txt";

        // 获取数据
        Set<String> url = redisUtil.getSet("URL");

        // 写入数据
        try (FileWriter writer = new FileWriter(fileName)) {
            for (String s : url) {
                s = s.substring(0, s.length() - 3);
                writer.write(s + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "FAIL";
        }
        return "SUC";
    }

    @GetMapping("/saveEmoticon")
    public String saveEmoticon() throws InterruptedException {

        Long startTime = System.currentTimeMillis();

        // 获取数据
        Set<String> utilSet = redisUtil.getSet("URL");

        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = threadPoolConfig.getThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(utilSet.size());

        utilSet.forEach(url ->
            threadPoolExecutor.execute(() -> {
                new SaveEmoticonThread( url.substring(0 , url.length() - 3) , emoticonService).run();
                countDownLatch.countDown();
            })
        );
        log.info("全部提交完毕");
        log.info("准备等待线程池任务执行完毕");
        countDownLatch.await();

        log.info("消耗的时间:{}",System.currentTimeMillis() - startTime + "ms");

        return "全部线程执行完毕";

    }


    @GetMapping("/saveEmoticonToRedis")
    public String saveEmoticonToRedis() throws InterruptedException {

        Long startTime = System.currentTimeMillis();

        // 获取数据
        Set<String> utilSet = redisUtil.getSet("URL");

        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = threadPoolConfig.getThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(utilSet.size());

        utilSet.forEach(url ->
                threadPoolExecutor.execute(() -> {
                    new SaveEmoticonToRedis( url.substring(0 , url.length() - 3) , emoticonRedisUtil).run();
                    countDownLatch.countDown();
                })
        );
        log.info("全部提交完毕");
        log.info("准备等待线程池任务执行完毕");
        countDownLatch.await();

        log.info("消耗的时间:{}",System.currentTimeMillis() - startTime + "ms");

        return "全部线程执行完毕";

    }

    @GetMapping("/producePhone")
    public String producePhone(){
        ThreadPoolExecutor executor = threadPoolConfig.getThreadPool();
        for (int i = 1; i <= 1000; i++) {
            executor.execute(new ProducePhone(buildUrl(i) ,redisUtil));
            log.info("提交了{}个线程",i);
        }
        return "获取成功";
    }

    private static String buildUrl(int num){
        return  "https://www.zhongxinwanka.com/forum-93-"+ num +".html";
    }
}
